package org.sxp.common.customDialect;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.sxp.common.utils.SpringContextUtils;
import org.sxp.modules.sys.entity.SysDictEntity;
import org.sxp.modules.sys.service.SysDictService;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.engine.AttributeName;
import org.thymeleaf.model.IModel;
import org.thymeleaf.model.IModelFactory;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractAttributeTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.templatemode.TemplateMode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by klaus on 2018/5/18.
 */
public class DictSelectProcessor extends AbstractAttributeTagProcessor {
    private static final String DELIMITER = ",";
    private static final String ATTRIBUTE_NAME = "select";
    private static final int PRECEDENCE = 300;

    protected DictSelectProcessor( String dialectPrefix) {
        super(
                TemplateMode.HTML, // 处理thymeleaf 的模型
                dialectPrefix, // 标签前缀名
                null, // No tag name: match any tag name
                false, // No prefix to be applied to tag name
                ATTRIBUTE_NAME, // 标签前缀的 属性 例如：< risk:sansiEncrypt="">
                true, // Apply dialect prefix to attribute name
                PRECEDENCE, // Precedence (inside dialect's precedence)
                true); // Remove the matched attribute afterwards
    }

    @Override
    protected void doProcess(ITemplateContext context,
                             IProcessableElementTag tag, AttributeName attributeName,
                             String attributeValue, IElementTagStructureHandler structureHandler) {
        SysDictService dictService = SpringContextUtils.getBean(SysDictService.class);

        final String exper = ThymeleafFacade.getRawValue(tag, attributeName); //获取标签内容表达式
        String value = "";
        if(!StringUtils.isEmpty(exper)){
            //通过IStandardExpression 解析器 解析表达式获取参数
            final List<String> values = ThymeleafFacade.evaluateAsStringsWithDelimiter(context, exper, DELIMITER);
            value = values.size() > 0 && values.size() == 1 ? values.get(0) : "";
        }

        final String elementCompleteName = tag.getElementCompleteName(); //标签名

        //创建模型
        final IModelFactory modelFactory = context.getModelFactory();
        final IModel model = modelFactory.createModel();

        //添加默认选项
        if(tag.getAttribute("default") != null){
            String val = tag.getAttribute("defaultVal") != null ? tag.getAttribute("defaultVal").getValue() : "";
            if(StringUtils.isBlank(exper)){
                model.add(modelFactory.createOpenElementTag("option value='"+val+"' selected"));
            }else{
                model.add(modelFactory.createOpenElementTag("option value='"+val+"'"));
            }

            if(!StringUtils.isEmpty(tag.getAttributeValue("default"))){
                model.add(modelFactory.createText(tag.getAttributeValue("default")));
            }else{
                model.add(modelFactory.createText("--请选择--"));
            }
            model.add(modelFactory.createCloseElementTag("option"));
        }
        //添加模型 标签
        Map<String,String> options=new HashMap<String, String>();
        List<SysDictEntity> dictEntities = dictService.list(
                new LambdaQueryWrapper<SysDictEntity>()
                        .eq(SysDictEntity::getType, tag.getAttribute("dictType").getValue())
        );


        for(SysDictEntity dictDO : dictEntities){
            if(dictDO.getValue().equals(value)){
                model.add(modelFactory.createOpenElementTag("option value='"+dictDO.getCode()+"' selected"));
            }else{
                model.add(modelFactory.createOpenElementTag("option value='"+dictDO.getCode()+"'"));
            }
            model.add(modelFactory.createText(dictDO.getValue()));
            model.add(modelFactory.createCloseElementTag("option"));
        }

        //添加模型 标签
        model.add(modelFactory.createCloseElementTag(elementCompleteName));

        structureHandler.insertImmediatelyAfter(model, false);
        //替换页面标签
//        structureHandler.replaceWith(model, false);
    }

}
